<template>
  <el-dialog :model-value="dialogAdd" width="45%" :before-close="handleClose">
    <template #header>
      <h3 style="padding-bottom: 10px">添加场地</h3>
    </template>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="auto">
      <el-form-item label="场地名称：" prop="spaceName">
        <el-input
          v-model="form.spaceName"
          placeholder="请输入场地名称"
          clearable
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="场地类型：" prop="typeId">
        <el-select
          v-model="form.typeId"
          placeholder="请选择场地类型"
          clearable
          @focus="VenueList"
          :loading="loading"
        >
          <el-option
            v-for="item in ParentList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容：" prop="spaceInfo">
        <WangEditor
          v-model="form.spaceInfo"
          height="200"
          @change="handleEditorChange"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">添加</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import WangEditor from '@/components/WangEditor/index.vue';
import { addActivityVenue } from '@/api/Activity/venue';
import { getActivityVenueType } from '@/api/Activity/venue';

// 添加用户数据
const form = ref({
  spaceName: '',
  typeId: '',
  spaceInfo: '',
});
const loading = ref(false);
const ParentList = ref([]);

// 校验规则
const formRef = ref(null);
const rules = {
  spaceName: [{ required: true, message: '请输入场地名称', trigger: 'blur' }],
  typeId: [{ required: true, message: '请选择场地类型', trigger: 'change' }],
  spaceInfo: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '<p><br></p>') {
          callback(new Error('请输入内容'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

// 定义 props，接收父组件传递的数据
defineProps({
  dialogAdd: {
    type: Boolean,
  },
});

// 定义 emits，向父组件发送事件
const emit = defineEmits(['confirm', 'cancel']);
// 处理编辑器内容变化
const handleEditorChange = (html) => {
  form.value.spaceInfo = html;
  // 手动触发表单验证
  formRef.value?.validateField('spaceInfo');
};
// 处理取消按钮的点击事件
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {};
  ParentList.value = [];
  emit('cancel');
};

// 处理确认按钮的点击事件
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await addActivityVenue({ ...form.value });
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '添加成功',
          type: 'success',
        });
        emit('confirm');
        handleClose();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    }
  });
};

// 获取活动分类下拉
const getActivityVenueList = async () => {
  loading.value = true;
  try {
    const res = await getActivityVenueType({});
    if (res.data.code === 200) {
      ParentList.value = res.data.data;
    } else {
      // eslint-disable-next-line no-undef
      ElMessage({
        message: res.data.msg,
        type: 'error',
      });
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
  } finally {
    loading.value = false;
  }
};
const VenueList = () => {
  getActivityVenueList();
};
// 关闭对话框
const handleClose = () => {
  handleCancel();
};

onMounted(() => {});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
